#coding:utf-8

import re
import requests
import os


def dowmloadPic(html, keyword):
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    print('找到关键词:' + keyword + '的图片，开始下载图片...')
    for imageUrl in pic_url:
        print('正在下载第' + str(i) + '张图片，图片地址:' + str(imageUrl))
        try:
            pic = requests.get(imageUrl, timeout=100)
        except requests.exceptions.ConnectionError:
            print('当前图片下载失败')
            continue        
        dir = './images/' + keyword + '_' + str(i) + '.jpg'
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        i += 1


if __name__ == '__main__':
    word = input("请输入你要搜索的图片: ")
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&ct=201326592&v=flip'
    print(url)
    result = requests.get(url)
    dirs = './images/'
    if not os.path.exists(dirs):
         os.makedirs(dirs)
    dowmloadPic(result.text, word)
    input()